<template>
  <p-modal
    title="开班检验"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <p-spin :spinning="confirmLoading">
      <p-form-model
        ref="form"
        :model="model"
        :rules="validatorRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <p-row :gutter="24">
          <p-col :span="8">
            <p-form-model-item
              label="车间"
              prop="classtimeno"
            >
              <p-input
                disabled
                placeholder="自动带入"
                v-model.trim="model.workroomname"
              ></p-input>
            </p-form-model-item>
          </p-col>
          <p-col :span="8">
            <p-form-model-item
              label="线体"
              prop="linename"
            >
              <p-input
                disabled
                placeholder="自动带入"
                v-model.trim="model.linename"
              ></p-input>
            </p-form-model-item>
          </p-col>
          <p-col :span="8">
            <p-form-model-item
              label="检验单号"
              prop="orderNo"
            >
              <p-input
                disabled
                v-model.trim="model.orderNo"
                placeholder="依据规则自动生成"
              ></p-input>
            </p-form-model-item>
          </p-col>
        </p-row>
        <p-row :gutter="24">
          <p-col :span="8">
            <p-form-model-item
              label="日期"
              prop="startDate"
            >
              <p-date-picker
              @change="getProcessId"
                format="YYYY-MM-DD"
                v-model.trim="model.startDate"
                :defaultValue="valueData"
                placeholder="请选择日期"
              />
            </p-form-model-item>
          </p-col>
          <p-col :span="8">
            <p-form-model-item
              label="工序工单"
              prop="processId"
            >
              <p-select
                placeholder="显示当前线体工序工单"
                v-model.trim="model.processId"
                @change="changeProcess"
              >
                <p-select-option
                  v-for="list in processList"
                  :value="list.id"
                  :key="list.id"
                >{{list.processbillno}}</p-select-option>
              </p-select>
            </p-form-model-item>
          </p-col>
          <p-col :span="8">
            <p-form-model-item
              label="产品类别"
              prop="productType"
            >
              <p-input
                disabled
                v-model.trim="model.productType"
                placeholder="自动带入"
              ></p-input>
            </p-form-model-item>
          </p-col>
        </p-row>
        <p-row :gutter="24">
          <p-col :span="8">
            <p-form-model-item
              label="产品编码"
              prop="productCode"
            >
              <p-input
                disabled
                v-model.trim="model.productCode"
                placeholder="选择工单自动带出"
              ></p-input>
            </p-form-model-item>
          </p-col>

          <p-col :span="8">
            <p-form-model-item
              label="工单类型"
              prop="processType"
            >
              <p-select
                disabled
                placeholder="选择工单自动带出"
                v-model.trim="model.processType"
              >
                <p-select-option
                  v-for="list in processTypes"
                  :value="list.value"
                  :key="list.value"
                >{{list.text || list.title}}</p-select-option>
              </p-select>
            </p-form-model-item>
          </p-col>

          <p-col span="8">
            <p-form-model-item
              label="检验模板"
              prop="templateKey"
            >
              <p-select
                style="width:170px;margin-right:5px"
                placeholder="带出工厂主数据模板名称"
                v-model.trim="model.templateKey"
                @change="changeTemplate"
              >
                <p-select-option
                  v-for="list in templateList"
                  :value="list.checkno"
                  :key="list.id"
                >{{list.checkname}}</p-select-option>
              </p-select>
              <p-button
                type="primary"
                @click="handleCheck"
              >检验</p-button>
            </p-form-model-item>
          </p-col>
        </p-row>
        <!--开班检查详情-->
        <classDetail-table
          ref="linksRef"
          :dictOptions="dictOptions.method"
        ></classDetail-table>

        <div class="relate-class-list">
          <h3 class="title">关联工序工单</h3>
          <p-checkbox
            v-if="options && options.length"
            :indeterminate="indeterminate"
            :checked="checkAll"
            @change="onCheckAllChange"
          >
            全选
          </p-checkbox>
          <br />
          <div class="list">
            <p-checkbox-group
              v-model.trim="checkedList"
              :options="options"
              @change="onChange"
            />
          </div>
        </div>
      </p-form-model>
    </p-spin>
  </p-modal>
</template>

<script>
import { httpAction, api, getAction, putAction, postAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { SubmitOnchangMixin } from '@/mixins/SubmitOnchangMixin'
import pick from 'lodash.pick'
import { validateDuplicateValue } from '@/utils/util'
import ClassDetailTable from '../components/ClassDetailTable'
import { initDictOptions, filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import _find from 'lodash/find'
import _uniqBy from 'lodash/uniqBy'
import moment from 'moment'

export default {
  name: "MesBaStationModal",
  mixins: [SubmitOnchangMixin],
  props:['EnhanceJS'],
  components: {
    ClassDetailTable
  },
  data () {
    return {
      moment,
       valueData:'',
      form: this.$form.createForm(this),
      width: 1000,
      visible: false,
      model: {
        classtimeno: '',
        linename: '',
        orderNo: '',
        startDate: '',
        processId: '',
        productType: '',
        productCode: '',
        processType: '',
        templateKey: ''
      },
      confirmLoading: false,
      validatorRules: {
        classtimeno: [{ required: true, message: '请输入 ' }],
        linename: [{ required: true, message: '请输入 ' }],
        orderNo: [],
        startDate: [{ required: true, message: '请输入 ' }],
        processId: [{ required: true, message: '请输入 ' }],
        // productType: [{ required: true, message: '请输入 ' }],
        productCode: [{ required: true, message: '请输入 ' }],
        processType: [{ required: true, message: '请输入 ' }],
        templateKey: [{ required: true, message: '请选择 ' }],
      },
      url: {
        detail: '/mes-manufacture/mfClassTest/getFilterDetail', // 打开弹窗后，开班检验值
        add: '/mes-manufacture/mfClassTest/link',
        submitCheck: '/mes-manufacture/mfClassTest/submit', // 确认检验
        allCheckTemplate: '/basic-business/mesBaChecktemplate/checktemplateList', // 所有开班检查模板列表 
      },
      dictOptions: {
        method: []
      },
      checkedList: [],
      indeterminate: true,
      checkAll: false,
      options: [],
      processList: [], // 工序工单列表
      processTypes: [], // 工单类型下拉值
      templateList: [], // 全部开班检查模板
      templateListTemp: [],
      templateObj: null // 开班检查模板对象
    }
  },
  computed: {
  },
  // watch:{
  //   EnhanceJS(){
     
  //     this.valueData=moment(this.setData(),"YYYY-MM-DD'")
  //     this.model.startDate=this.valueData
  //     this.getProcessId()
  //   }
  // },
  
  methods: {
    //设置默认时间为当天
  setData(){
    let now=new Date()
    let year=now.getFullYear();  //取得4位数的年份
    let month=now.getMonth()+1;  //取得日期中的月份，其中0表示1月，11表示12月
    let date=now.getDate();      //返回日期月份中的天数（1到31）
   return year+"-"+month+"-"+date;
  },
    changeTemplate (val) {
      if (val) {
        let item = _find(this.templateList, { checkno: val })
        if (item) this.templateObj = item
      } else {
        this.templateObj = null
      }
    },
    // 更换工单工序
    changeProcess (val) {
      if (val) {
        let item = _find(this.processList, { id: val })
        if (item) {
          this.model = Object.assign(this.model, {
            classtimeno: item.classtimeno,
            linename: item.linename.trim(),
            orderNo: this.model.orderNo,
            productType: item.productType,
            productCode: item.productCode,
            processType: item.processType + '',
            workroomno:this.EnhanceJS.workroomno,
            workroomname:this.EnhanceJS.workroomname
          })

          // 根据工序工单自动带出产品编码，根据产品编码带出检验模板
          this.filterTemplateByMcode(this.model.productCode)
          this.options = item.linkeds.map(v => {
            return {
              label: v.textValue,
              value: v.codeValue
            }
          }) || []
        }
      }
    },
    // 根据产品编码过滤出开班检查模板
    filterTemplateByMcode (productCode) {
      let template = this.templateListTemp
      let result = []
      console.log(template)
      template.map(v => {
        if (v.lists && v.lists.length) {
          v.lists.map(i => {
            if (i.mcode == productCode) {
              result.push(v)
            }
          })
        }
      })
      if (result && result.length === 1) {
        this.templateList = result
        // 自动填充值
        this.model.templateKey = result[0].checkno
      } else {
        this.templateList = _uniqBy(result, 'id')
      }
    },
    add () {
      this.resetData()
      this.getAllTemplate()
      this.getDicOptions()
      this.getData()
      this.getRuleCodeValue()
      this.valueData=moment(this.setData(),"YYYY-MM-DD'")
      this.model.startDate=this.valueData
      this.getProcessList()
      this.visible = true;
    },
    edit (record) {
      this.resetData()
      // this.model = Object.assign({}, record);
      this.visible = true;
    },
    resetData () {
      this.model = {}
      this.$refs.form?.resetFields()
      if (this.$refs.linksRef) this.$refs.linksRef.dataList = []
      this.templateList = []
      this.processList = []
      this.checkedList = []
      this.options = []
      this.templateObj = null
      this.checkAll = false
      this.indeterminate = false
    },
    // 获取所有开班检查模板
    getAllTemplate () {
      let data={
        lineno:this.model.lineno,
        starttime:this.model.starttime,
        workroomno:this.model.workroomno,
        status:0
      }
      getAction(this.url.allCheckTemplate,data).then(res => {
        if (res.code == 0) {
          this.templateListTemp = res.data || []
        }
      })
    },
    getData () {
      this.employeeinfo = JSON.parse(localStorage.getItem('employeeinfo')) // 获取当前人员信息 
      if (this.employeeinfo) {
        // this.getProcessList()
        this.lineList = [{
          value: this.employeeinfo.lineno,
          label: this.employeeinfo.linename
        }]
      }
    },
    getProcessId(){
      this.getProcessList()
      this.changeProcess()
    },
    getProcessList () {
      getAction(this.url.detail, {
        lineno: this.EnhanceJS.lineno,
        workroomno: this.EnhanceJS.workroomno,
        status: '0',
        starttime:moment(this.model.startDate).format('YYYY-MM-DD 00:00:00'),
        endtime:moment(this.model.startDate).format('YYYY-MM-DD 23:59:59')
      }).then(res => {
        if (res.code == 0) {
          console.log('更新数据')
          this.processList = res.data
        }
      })
      
    },
    getDicOptions () {
      initDictOptions('mes_process_type').then((res) => {
        if (res.success) {
          this.processTypes = res.data
        }
      })
    },
    onChange (checkedList) {
      this.indeterminate = !!checkedList.length && checkedList.length < this.options.length;
      this.checkAll = checkedList.length === this.options.length;
    },
    onCheckAllChange (e) {
      let result = []
      if (e.target.checked) {
        this.options.filter(v => {
          result.push(v.value)
        })
      }
      this.checkedList = result
      this.indeterminate = false
      this.checkAll = e.target.checked
    },
    getRuleCodeValue () {
      const param = {
        commonFormData: null,
        rules: [{ ruleCode: 'mes_class_order_no', columnName: 'orderNo' }],
      }
      putAction(api.ruleBaseURL, param).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.orderNo = res.data.orderNo
        }
      })
    },
    close () {
      this.$emit('close');
      this.visible = false;
    },
    handleOk () {
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          let processType = _find(this.processTypes, { value: this.model.processType })
          processType = processType.text || processType.title
          if (processType.indexOf('中试') > -1 || processType.indexOf('科研') > -1) {
            this.$confirm({
              title: '提醒',
              content: `工单为${processType}，是否满足开班需求？`,
              onOk () {
                this.submit()
              },
              onCancel () { }
            })
          } else {
            this.submit()
          }
        }
      })
    },
    submit () {
      let params = {
        id: this.model.processId,
        elements: this.checkedList
      }
      postAction(this.url.add, params).then(res => {
        if (res.code == 0) {
          this.$message.success(res.msg)
          this.$emit('ok')
          this.close()
        } else {
          this.$message.warning(res.msg);
        }
      })
    },
    // 确认检验模板
    handleCheck () {
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          let params = {
            id: this.model.processId,
            templateKey: this.model.templateKey,
            startDate: this.model.startDate,
            orderNo: this.model.orderNo
          }
          postAction(this.url.submitCheck, params).then(res => {
            if (res.code == 0) {
              // 获取开班检查详情列表
              this.$message.success('检验成功')
              this.$refs.linksRef.dataList = res.data || []
              this.$emit('ok') // 刷新列表
            }
          })
        }
      })
    },
    handleCancel () {
      this.close()
    },
  },
 
}
</script>
<style lang="less" scoped>
.relate-class-list {
  margin-top: 20px;
  .title {
    font-size: 14px;
    line-height: 22px;
    padding-left: 13px;
    margin: 20px 0;
    border-left: 4px solid rgb(64, 100, 223);
  }
  .list {
    height: 110px;
    padding-top: 6px;
    overflow: auto;
  }
}
</style>